//
//  JsBridge.m
//  SHNet
//
//  Created by FranklinPhill on 16/1/7.
//  Copyright © 2016年 Fire. All rights reserved.
//

#import "JsBridge.h"
#import "WebViewJavascriptBridge.h"
#import "JSONkit.h"

@interface JsBridge(){
    NSMutableDictionary *apiDic;
    JsBridge *apiBridge;
    WebViewJavascriptBridge *_bridge;
}

@end

@implementation JsBridge

- (id)initWithWebView:(UIWebView *)webView withDelegate:(id<UIWebViewDelegate>)delegate {
    apiDic = [[NSMutableDictionary alloc] init];
    apiBridge = self;
    [WebViewJavascriptBridge enableLogging];
    _bridge = [WebViewJavascriptBridge bridgeForWebView:webView webViewDelegate:delegate handler:^(id data, WVJBResponseCallback responseCallback) {
//        DLog(@"ObjC received message from JS: %@", data);
    }];
    [_bridge registerHandler:@"invoke" handler:^(id data, WVJBResponseCallback responseCallback) {
//        DLog(@"invoke: %@", data);
        NSDictionary *dataDic = (NSDictionary*)data;
        NSString *api = [dataDic objectForKey:@"api"];
        NSDictionary *args = [dataDic objectForKey:@"params"];
        NSNumber *reqCode = [dataDic objectForKey:@"code"];
//        NSLog(@"api dict:%@", apiDic);
        id<WebViewApiDelegate> webApi = [apiDic objectForKey:api];
        if (webApi == nil) {
            NSMutableDictionary *response = [[NSMutableDictionary alloc] init];
            [response setObject:reqCode forKey:@"code"];
            NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
            [result setObject:@"api not implement" forKey:@"error"];
            //[result setObject:[[NSNumber alloc] initWithInt:0] forKey:@"success"];
            [response setObject:result forKey:@"result"];
            responseCallback(response);
        } else {
            [webApi invoke:apiBridge api:api callback:responseCallback withArgs:args reqCode:reqCode];
        }
        
    }];
    return [super init];
}

- (void)addWebViewApi:(id<WebViewApiDelegate>)webViewApi {
    NSArray *apis = [webViewApi getWebApiNames];
    for (int i = 0; i < [apis count]; i++) {
        [apiDic setObject:webViewApi forKey:[apis objectAtIndex:i]];
    }
}

- (void)callback:(WVJBResponseCallback)responseCallback withReqCode:(NSNumber *)code withResult:(NSObject *)object {
    NSMutableDictionary *response = [[NSMutableDictionary alloc] init];
    [response setObject:code forKey:@"code"];
    [response setObject:object forKey:@"result"];
    responseCallback(response);
}

- (void)jsInvoke:(NSString *)api args:(NSDictionary *)args handler:(JsHandler)handler {
    [_bridge callHandler:@"invoke" data:[NSDictionary dictionaryWithObjectsAndKeys:api,@"api", args, @"args", nil] responseCallback:^(id responseData) {
//        DLog(@"Current UIWebView page URL is: %@", responseData);
        if (handler) {
            handler(responseData);
        }
    }];
}

- (void)releaseJsBridge {
    _bridge = nil;
}

@end